package util

import (
	"github.com/mroth/weightedrand/v2"
	"go_server/zinx/zlog"
	"math/rand"
	"time"
)

func NewRand() *rand.Rand {
	return rand.New(rand.NewSource(time.Now().UnixNano()))
}

type integer interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

// 获得随机权重
func GetRandWeight[T comparable, W integer](weights map[T]W) (T, bool) {
	var rstKey T
	if len(weights) <= 0  {
		return rstKey, false
	}

	weightArr := make([]weightedrand.Choice[T, W], 0, len(weights))
	for item, weight := range weights {
		weightArr = append(weightArr, weightedrand.NewChoice[T, W](item,weight))
	}
	chooser, err := weightedrand.NewChooser[T, W](weightArr...)
	if err != nil {
		zlog.Errorf("weightedrand.NewChooser err!!!, err: %v", err)
		return rstKey, false
	}

	return chooser.Pick(), true
}
